package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.VideoUploadInfo;
import com.letv.whatslive.model.convert.VideoUploadInfoConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by haojiayao on 16-3-29.
 */
@Repository
public class VideoUploadInfoDAO extends BaseDAO {

    private final static Logger logger = LoggerFactory.getLogger(VideoUploadInfoDAO.class);

    protected String collectionName = "videoUploadInfo";

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    /**
     * 插入视频信息
     *
     * @param videoUploadInfo
     * @return
     */
    public long insertVideoUploadInfo(VideoUploadInfo videoUploadInfo) {
        DBObject obj = VideoUploadInfoConvert.castVideoUploadInfoToDBObject(videoUploadInfo);
        return this.insert(obj);
    }

    /**
     * 更新视频上传信息
     *
     * @param videoUploadInfo
     */
    public void updateVideoUploadInfo(VideoUploadInfo videoUploadInfo) {

        try {

            DBObject queryCondition = new BasicDBObject();
            Long id = videoUploadInfo.getId();
            queryCondition.put("_id", id);
            BasicDBObject setValue = (BasicDBObject) VideoUploadInfoConvert.castVideoUploadInfoToDBObject(videoUploadInfo);
            DBObject updateValue = new BasicDBObject("$set", setValue);
            this.dbCollection.update(queryCondition, updateValue);
        } catch (Exception e) {

            logger.error("updateVideoUploadInfo error", e);
        }
    }

    /**
     * 更新视频上传状态
     *
     * @param status 视频上传状态
     */
    public void updateVideoUploadStatus(Long outKey, Integer status) {
        try {
            DBObject queryCondition = new BasicDBObject();
            queryCondition.put("outKey", outKey);
            BasicDBObject setValue = new BasicDBObject();
            setValue.put("updateTime", System.currentTimeMillis());
            setValue.put("status", status);
            DBObject updateValue = new BasicDBObject("$set", setValue);
            this.dbCollection.update(queryCondition, updateValue);
        } catch (Exception e) {

            logger.error("updateVideoUploadStatus error", e);
        }
    }

    /**
     * 根据outKey查询视频上传信息
     *
     * @param outKey
     * @return
     */
    public VideoUploadInfo getVideoUploadInfoByOutKey(Long outKey) {

        VideoUploadInfo videoUploadInfo = null;
        try {
            DBObject dbObject = new BasicDBObject();
            dbObject.put("outKey", outKey);

            DBObject result = dbCollection.findOne(dbObject);
            if (result == null) {

                return null;
            }

            videoUploadInfo = VideoUploadInfoConvert.castDBObjectToVideoUploadInfo(result);
        } catch (Exception e) {

            logger.error("getVideoUploadInfoByOutKey error, outKey==" + outKey, e);
        }

        return videoUploadInfo;
    }

    /**
     * 根据条件查询视频上传列表
     *
     * @param params 查询参数
     * @param orders 排序参数
     */
    public List<VideoUploadInfo> getVideoUploadInfoListByParams(Map<String, Object> params, Map<String, Object> orders) {

        List<VideoUploadInfo> videoUploadInfoList = Lists.newArrayList();

        try {

            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {

                DBObject dbObject = cur.next();
                VideoUploadInfo videoUploadInfo = VideoUploadInfoConvert.castDBObjectToVideoUploadInfo(dbObject);
                videoUploadInfoList.add(videoUploadInfo);
            }
        } catch (Exception e) {

            logger.error("getVideoUploadInfoListByParams error", e);
        }
        return videoUploadInfoList;
    }

    /**
     * 根据查询参数Map获取查询条件对象
     *
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params) {

        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {

            if (params.get("outKey") != null) {
                query.put("outKey", ObjectUtils.toLong(params.get("outKey")));
            }
        }

        return query;
    }

    /**
     * 获取排序对象
     *
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {

        BasicDBObject order = new BasicDBObject();

        if (null != orders && orders.size() > 0) {

            for (String key : orders.keySet()) {

                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        } else {
            //默认按照创建时间排序
            order.append("createTime", -1);
        }
        return order;
    }

    /**
     * 根据视频ID查询视频上传信息
     *
     * @param vid 视频ID
     * @return
     */
    public VideoUploadInfo getVideoUploadInfoByVid(Long vid) {

        VideoUploadInfo videoUploadInfo = null;
        try {
            DBObject dbObject = new BasicDBObject();
            dbObject.put("vid", vid);

            DBObject result = dbCollection.findOne(dbObject);
            if (result == null) {

                return null;
            }

            videoUploadInfo = VideoUploadInfoConvert.castDBObjectToVideoUploadInfo(result);
        } catch (Exception e) {

            logger.error("getVideoUploadInfoByVid error, vid==" + vid, e);
        }

        return videoUploadInfo;
    }
}
